package com.zhugang.week13.binarysearch;

/**
 * @program algorithms
 * @description: BinarySearchLastLessThan
 * @author: chanzhugang
 * @create: 2022/11/25 19:23
 */
public class BinarySearchLastLessThan {

    /**
     * 查找最后一个值小于等于给定元素的下标
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bsearch(int[] a, int n, int target) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] <= target) {
                // 向后探测，不满足条件，当前mid是最后一个小于等于target元素的下标
                if (mid == n - 1 || a[mid + 1] > target) {
                    return mid;
                } else {
                    low = mid + 1;
                }
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchLastLessThan binarySearchLastLessThan = new BinarySearchLastLessThan();
        int[] a = {1, 3, 5, 6, 6, 8, 10};
        int index = binarySearchLastLessThan.bsearch(a, a.length, 6);
        System.out.println(index);
    }
}